<template>
  <div class="table">
    <div class="row head">
      <div class="span">字段名称</div>
      <div class="span">字段类型</div>
      <!-- <div class="switch">是否必填</div>
      <div class="switch">是否开启</div> -->
      <div class="action">操作</div>
    </div>
    <Draggable
      v-if="dataSourceCopy.length > 0"
      v-model="dataSourceCopy"
      group="sjgk"
      animation="300"
      filter=".undraggable"
      @end="onDragEnd"
    >
      <div v-for="(li, idx) in dataSourceCopy" :key="li.fieldName" class="row" :class="li.fieldSource === 1 ? 'undraggable' : 'draggable'">
        <div class="span">{{ li.fieldName }}</div>
        <div class="span">{{ fieldTypeMap[li.fieldType] }}</div>
        <!-- <div class="switch">
          <a-switch
            :checked="li.isNecessary"
            :disabled="li.fieldSource === 1"
            size="small"
            @change="(checked) => onNecChange(checked, idx)"
          />
        </div>
        <div class="switch">
          <a-switch :checked="li.isOpen" :disabled="li.fieldSource === 1" size="small" @change="(checked) => onOpenChange(checked, idx)" />
        </div> -->
        <div class="action">
          <a-space>
            <a-icon v-if="editIcon" type="edit" :class="{ able: li.fieldSource !== 1 }" @click="onEditItem(idx, li.fieldSource === 1)" />
            <a-popconfirm title="确认要删除字段吗" @confirm="onDelItem(idx, li.fieldSource === 1)">
              <a-icon v-if="deleteIcon" type="delete" :class="{ able: li.fieldSource !== 1 }" />
            </a-popconfirm>
            <a-icon type="drag" :class="{ able: li.fieldSource !== 1 }" />
          </a-space>
        </div>
      </div>
    </Draggable>
    <a-empty v-else class="empty">
      <div slot="image"></div>
      <div slot="description" style="padding: 16px; color: #ddd">暂无数据</div>
    </a-empty>
    <div v-if="addIcon" class="addBtn" @click="onAddItem">
      <a-icon type="plus" style="margin-right: 8px" />
      新增自定义字段
    </div>
    <a-modal
      :title="modalTitle"
      :visible="modalVisible"
      :confirmLoading="confirmLoading"
      class="form"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-form-model ref="ruleForm" class="form" :model="form" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-model-item
          help="1-20个字符，不能与现有字段重复"
          ref="fieldName"
          :rules="[{ required: true, message: '请输入字段名称' }]"
          label="字段名称"
          prop="fieldName"
        >
          <a-input allowClear v-model="form.fieldName" placeholder="请输入字段名称" :max-length="20" />
        </a-form-model-item>
        <a-form-model-item ref="fieldType" :rules="[{ required: true, message: '请选择字段类型' }]" label="字段类型" prop="fieldType">
          <a-select
            allowClear
            :disabled="modalMode === 'edit' ? true : false"
            v-model="form.fieldType"
            placeholder="请选择字段类型"
            style="width: 100%"
            @change="fieldTypeChange"
          >
            <a-select-option :value="item.k" v-for="item in fieldTypeArr" :key="item.k">{{ item.v }}</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="选项值" v-if="form.fieldType == '1'" :label-col="{ span: 5 }" :wrapper-col="{ span: 22 }">
          <div v-for="(item, index) in form.options" :key="index" style="display: flex; align-items: center; width: 80%; margin: 0 auto">
            <div style="width: 120px">{{ `选项 ${index}` }}</div>
            <a-input allowClear v-model="form.options[index]" placeholder="请输入字段名称" :max-length="15" />
            <a-icon
              v-if="form.options.length > 1"
              :disabled="form.options.length === 1"
              type="delete"
              style="margin: 0 15px; cursor: pointer"
              @click="removeOption(index)"
            />
          </div>
          <div style="text-align: center; margin-top: 12px">
            <a-button type="dashed" style="width: 80%" @click="addDomain">
              <a-icon type="plus" />
              添加自定义选项
            </a-button>
          </div>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>
<script>
import Draggable from "vuedraggable";
import { fieldTypeArr, fieldTypeMap } from "./templateConfigTableFuncs";
export default {
  name: "",
  components: { Draggable },
  mixins: [],
  props: {
    dataSource: {
      type: Array,
      default: () => []
    },
    editIcon: {
      type: Boolean,
      default: true
    },
    deleteIcon: {
      type: Boolean,
      default: true
    },
    addIcon: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      fieldTypeArr,
      fieldTypeMap,
      labelCol: { span: 6 },
      wrapperCol: { span: 14 },
      modalMode: "add",
      modalTitle: false,
      modalVisible: false,
      confirmLoading: false,
      form: {
        options: []
      },
      editItemIndex: null,
      dataSourceCopy: []
    };
  },
  computed: {},
  watch: {
    dataSource: {
      handler(val) {
        this.dataSourceCopy = val;
      },
      immediate: true
    }
  },
  created() {},
  mounted() {},
  methods: {
    addDomain() {
      this.form = {
        ...this.form,
        options: [...this.form.options, ""]
      };
    },
    fieldTypeChange(index) {
      if (index === 1) {
        this.form = {
          ...this.form,
          options: [""]
        };
      } else {
        this.form = {
          ...this.form,
          options: null
        };
      }
    },
    removeOption(index) {
      const temp = [...this.form.options];
      temp.splice(index, 1);
      this.form = {
        ...this.form,
        options: temp
      };
    },
    onNecChange(checked, index) {
      this.$emit("editOk", {
        params: { isNecessary: checked },
        mode: "edit",
        index
      });
    },
    onOpenChange(checked, index) {
      this.$emit("editOk", {
        params: { isOpen: checked },
        mode: "edit",
        index
      });
    },
    handleOk() {
      this.confirmLoading = true;
      this.$refs.ruleForm.validate((valid, res) => {
        console.log("fieldEdit", valid, res);
        if (valid) {
          const _form = JSON.parse(JSON.stringify(this.form));
          let flag = false;
          if (_form.fieldType === 1) {
            _form.options.forEach((item, index) => {
              if (item === "") {
                flag = true;
              }
            });
          }
          if (flag) {
            this.$notification["error"]({
              message: "error",
              description: "自定义选项不能为空"
            });
            return false;
          } else {
            if (_form.fieldType === 1) {
              _form.options = _form.options.join(",");
            }
            this.$emit("editOk", {
              params: _form,
              mode: this.modalMode,
              index: this.modalMode === "edit" ? this.editItemIndex : null
            });
            this.handleCancel();
          }
        } else {
          return false;
        }
      });
      this.confirmLoading = false;
    },
    handleCancel() {
      this.modalVisible = false;
    },
    onEditItem(idx, isDisabled) {
      if (isDisabled) {
        return false;
      }
      this.editItemIndex = idx;
      this.modalMode = "edit";
      this.modalTitle = "编辑字段";
      this.form = {
        ...this.dataSourceCopy[idx],
        options: this.dataSourceCopy[idx].options ? this.dataSourceCopy[idx].options.split(",") : []
      };
      this.modalVisible = true;
    },
    onDelItem(idx, isDisabled) {
      if (isDisabled) {
        return false;
      }
      this.$emit("delItem", idx);
    },
    onAddItem() {
      this.modalMode = "add";
      this.modalTitle = "新增字段";
      this.form = {
        options: null
      };
      this.modalVisible = true;
    },
    onDragEnd(evt) {
      this.$emit("sortItem", evt.oldIndex, evt.newIndex);
    }
  }
};
</script>
<style lang="scss" scoped>
.table {
  line-height: 42px;
  .row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-bottom: 1px solid #e8e8e8;
    padding: 0 24px;
  }
  .head {
    background: rgba(250, 250, 250, 1);
    font-weight: 500;
  }
  .span {
    flex: 1;
  }
  .switch {
    width: 120px;
    flex-shrink: 0;
  }
  .action {
    width: 80px;
    flex-shrink: 0;
    text-align: right;
    ::v-deep .anticon {
      cursor: pointer;
    }
    .able {
      color: var(--primary);
    }
  }
  .draggable {
    cursor: move;
  }
  .addBtn {
    margin-top: 12px;
    line-height: 32px;
    cursor: pointer;
    color: var(--primary);
    border: 1px dashed var(--primary);
    border-radius: 4px;
    text-align: center;
  }
}

.empty {
  ::v-deep .ant-empty-image {
    display: none;
  }
}

.form {
  label {
    font-weight: 400;
  }
  ::v-deep .ant-form-explain {
    font-size: 12px;
  }
}
</style>
